﻿// <copyright file="MapPage.xaml.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2010-10-04</date>
// <summary>MapPage code behind</summary>

namespace MostPopular
{
    using System;
    using System.Device.Location;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Xml.Linq;
    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Controls.Maps;
    using NYTimes.Data;

    /// <summary>
    /// Page that displays a map of the geographic locations
    /// </summary>
    public partial class MapPage : PhoneApplicationPage
    {
        /// <summary>
        /// Initializes a new instance of the MapPage class
        /// </summary>
        public MapPage()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Look for the geographic facets using the Bing Maps Service
        /// </summary>
        /// <param name="sender">the map page</param>
        /// <param name="e">the routed event arguments</param>
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            var context = this.DataContext as MostPopularItem;

            var credentails = this.Map.CredentialsProvider as ApplicationIdCredentialsProvider;

            var bingMapsKey = credentails.ApplicationId; 

            foreach (var item in context.GeoFacets)
            {
                var client = new WebClient();

                client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(this.OnDownloadStringCompleted);

                var uriString = string.Format(
                    "http://dev.virtualearth.net/REST/{0}/Locations?query={1}&key={2}&o=xml",
                    "v1",
                    item,
                    bingMapsKey);

                System.Diagnostics.Debug.WriteLine(uriString);

                var address = new Uri(uriString, UriKind.Absolute);

                client.DownloadStringAsync(address);
            }
        }

        /// <summary>
        /// Add a pushpin for each location
        /// </summary>
        /// <param name="sender">the web client</param>
        /// <param name="e">the download string completed event arguments</param>
        private void OnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                System.Diagnostics.Debug.WriteLine(e.Error.Message);

                return;
            }

            var doc = XDocument.Parse(e.Result);

            var m = "{http://schemas.microsoft.com/search/local/ws/rest/v1}";

            var locations = doc.Root.Descendants(m + "Location");

            if (locations != null && locations.Count() > 0)
            {
                var location = locations.First();

                var pushpin = new Pushpin()
                {
                    Content = location.Element(m + "Name").Value
                };

                var point = location.Element(m + "Point");

                var coordinate = new GeoCoordinate(
                    double.Parse(point.Element(m + "Latitude").Value),
                    double.Parse(point.Element(m + "Longitude").Value));

                this.Locations.AddChild(pushpin, coordinate);
            }
        }
    }
}
